#include "hc_sr04.h"
#include "tim.h"


void HC_SR04_Init(void) {
    // GPIO已经在CubeMX中配置，这里不需要重复配置

    // 配置TIM2
    HAL_TIM_Base_Start_IT(&htim2);
}

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) {
    if (htim->Instance == TIM2) {
        Y_Out_Counter++;
    }
}

static void Timer_On(void) {
    __HAL_TIM_SET_COUNTER(&htim2, 0);
    Y_Out_Counter = 0;
    HAL_TIM_Base_Start(&htim2);
}

static void Timer_Off(void) {
    HAL_TIM_Base_Stop(&htim2);
}

static uint32_t Timer_Get_Counter(void) {
    uint32_t T;
    T = Y_Out_Counter * 100;
    T += __HAL_TIM_GET_COUNTER(&htim2);
    __HAL_TIM_SET_COUNTER(&htim2, 0);
    HAL_Delay(50);
    return T;
}

//float a = 0.0f;

float HC_SR04_GetLength(void) {
    int i;
    uint32_t t = 0;
    float Length = 0;
    float Sum = 0;

    for (i = 0; i < 3; i++) {
        HAL_GPIO_WritePin(GPIOA, GPIO_PIN_15, GPIO_PIN_SET);
        HAL_Delay(1);
        HAL_GPIO_WritePin(GPIOA, GPIO_PIN_15, GPIO_PIN_RESET);

        while (HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_12) == GPIO_PIN_RESET);

        Timer_On();


        while (HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_12) == GPIO_PIN_SET);

        Timer_Off();

        t = Timer_Get_Counter();

        Length = ((float) t / 58.0);

        Sum += Length;
    }

    Length = Sum / 3.0;
//    a = Length;
    return Length;
}
